<template>
  <div class="custom-detail">
    <HeaderNav :bgStyle="bgStyle" />
    <div class="custom-detail-main">
      <van-cell-group>
        <van-field
          class="search-input"
          v-model="searchValue"
          @update:model-value="getName"
          center
          clearable
          placeholder="请输入企业名搜索"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              style="margin-right: 0.5rem"
              color="#f56c6c"
              @click="cbeSync"
              >cbe同步</van-button
            >
            <van-button
              size="small"
              type="primary"
              color="#f56c6c"
              @click="searchCustom"
              >企查查同步</van-button
            >
          </template>
        </van-field>
      </van-cell-group>

      <van-cell-group class="mt-[1rem]">
        <van-form @submit="onSubmit" label-width="5rem">
          <van-cell-group inset>
            <van-field
              v-model="customerForm.zhName"
              name="中文名"
              label="中文名"
              placeholder="中文名"
              disabled
            />
            <van-field
              v-model="customerForm.zhShortName"
              name="中文简称"
              label="中文简称"
              placeholder="中文简称"
              disabled
            />
            <van-field
              v-model="customerForm.enName"
              name="英文名"
              label="英文名"
              placeholder="英文名"
              disabled
            />
            <van-field name="logo" label="logo" disabled>
              <template #input>
                <van-image
                  style="width: 6rem; height: 6rem"
                  :src="customerForm.logo"
                />
              </template>
            </van-field>
            <van-field name="radio" label="客户类型" disabled>
              <template #input>
                <van-radio-group
                  v-model="customerForm.customType"
                  direction="horizontal"
                  disabled
                >
                  <van-radio
                    v-for="dict of custom_type"
                    :label="dict.dictLabel"
                    :name="dict.dictValue"
                    :key="dict.dictValue"
                  >
                    {{ dict.dictLabel }}</van-radio
                  >
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              name="radio"
              label="展商类型"
              :disabled="customerForm.customType === '1'"
              v-if="customerForm.customType"
            >
              <template #input>
                <van-radio-group
                  class="radio-box"
                  v-model="customerForm.companyType"
                  direction="horizontal"
                  :disabled="customerForm.customType === '1'"
                >
                  <van-radio
                    v-for="dict of company_type"
                    :label="dict.dictLabel"
                    :name="dict.dictValue"
                    :key="dict.dictValue"
                  >
                    {{ dict.dictLabel }}</van-radio
                  >
                </van-radio-group>
              </template>
            </van-field>

            <van-field
              v-if="customerForm.companyType === '6'"
              v-model="customerForm.companyTypeOther"
              name="其他信息"
              label="其他信息"
              placeholder="其他信息"
            />

            <!--词条集合-->
            <template v-if="!loading">
              <span v-for="(item, index) of entryList" :key="index">
                <van-field
                  v-if="item.entryType === '1'"
                  v-model="item.content"
                  :name="item.entryTitle"
                  :label="item.entryTitle"
                  :placeholder="item.entryTitle"
                />

                <van-field
                  v-if="item.entryType === '4'"
                  v-model="item.content"
                  type="number"
                  :name="item.entryTitle"
                  :label="item.entryTitle"
                  :placeholder="item.entryTitle"
                />

                <van-field
                  :name="item.entryTitle"
                  :label="item.entryTitle"
                  v-if="item.entryType === '2'"
                  :placeholder="item.entryTitle"
                >
                  <template #input>
                    <van-radio-group
                      v-model="item.content"
                      direction="horizontal"
                    >
                      <van-radio
                        v-for="(sItem, inx) of item.optionVoList"
                        :key="inx"
                        :name="sItem.id"
                        >{{ sItem.optionName }}</van-radio
                      >
                    </van-radio-group>
                  </template>
                </van-field>

                <van-field
                  :name="item.entryTitle"
                  :label="item.entryTitle"
                  v-if="item.entryType === '3'"
                  :placeholder="item.entryTitle"
                >
                  <template #input>
                    <van-checkbox-group
                      v-model="item.content"
                      direction="horizontal"
                    >
                      <van-checkbox
                        v-for="(sItem, inx) of item.optionVoList"
                        :key="inx"
                        :name="sItem.id"
                        shape="square"
                      >
                        {{ sItem.optionName }}</van-checkbox
                      >
                    </van-checkbox-group>
                  </template>
                </van-field>
              </span>
            </template>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button
              block
              type="primary"
              color="linear-gradient(to right, #ffadb3, #ff4350)"
              native-type="submit"
            >
              提交
            </van-button>
          </div>
        </van-form>
      </van-cell-group>
    </div>
  </div>
</template>

<script setup lang="ts" name="CustomDetail">
import { computed, ref, watch } from "vue";
import HeaderNav from "@/components/headerNav/index.vue";
import useUserStore from "@/store/modules/user";
import { useRoute, useRouter } from "vue-router";
import { dictListAll } from "@/api/dict";
import { entryGetList } from "@/views/home/custom/comp/questionInfo/fetchData";
import { saveCustom, updateCustom } from "@/views/home/fetchData";
import {
  closeToast,
  showLoadingToast,
  showSuccessToast,
  showToast
} from "vant";
import dayjs from "dayjs";
import {
  customDetail,
  queryQccInfo,
  synCbeInfo
} from "@/views/home/custom/fetchData";
import { getLogo } from "@/utils";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const custom_type = ref<Record<string, any>[]>([]);
const company_type = ref<Record<string, any>[]>([]);
const entryList = ref<Record<string, any>[]>([]);
const customerForm = ref<Record<string, any>>({});
const customId = computed(() => route.query.customId as string);
const bgStyle = computed(() => {
  return {
    background: `url(${getLogo(customerForm.value.logo)}) no-repeat center`
  };
});
const searchValue = ref("");
const isCbe = ref(false);
const initForm = () => {
  return {
    belongOrg: null,
    brandInfoVoList: [],
    brandInfoBoList: [],
    companyType: "",
    contentVoList: [],
    customAreaVo: {
      province: "",
      city: "",
      county: ""
    },
    customCategoryBo: {
      brandId: "",
      categoryOne: "",
      categoryTwo: "",
      mainPush: "",
      entityType: "",
      customId: ""
    },
    customType: "",
    econKind: null,
    enName: "",
    entType: null,
    id: "",
    isOnStock: "0",
    logo: "",
    no: "",
    originalNameVoList: [],
    revokeInfoVo: {
      cancelReason: "",
      cancelDate: "",
      revokeReason: "",
      revokeDat: ""
    },
    stockType: "",
    zhName: "",
    zhShortName: "",
    briefIntro: "",
    externalTrade: "",
    externalTradeRatio: "",
    customMade: "",
    area: "",
    serviceScope: "",
    filings: "",
    annualOutput: "",
    annualValue: "",
    researchStaffNum: "",
    filingsNum: "",
    cbeSynDate: "",
    qccSynDate: ""
  };
};

function getName() {
  customerForm.value.zhName = searchValue.value;
}

function cbeSync() {
  if (!searchValue.value) return showToast("请输入企业名称");
  synCbeInfo(searchValue.value, customerForm.value.sourceId).then(
    (res: any) => {
      isCbe.value = +res.code === 200;
      if (+res.code === 200) {
        showToast("cbe同步成功");
        const data = res.data;
        customerForm.value.cbeSynDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
        customerForm.value.customType = data?.customType || "2";
        if (data) {
          customerForm.value.zhName = data.zhName;
          customerForm.value.zhShortName = data.zhShortName;
          customerForm.value.enName = data.enName;
          customerForm.value.logo = data.logo;
          customerForm.value.companyType = data.companyType;
          customerForm.value.briefIntro = data.briefIntro;

          // 日化展商 专业展商
          if (["1", "2"].includes(data.companyType)) {
            // 品牌字段
            const brandInfoVoList = customerForm.value.brandInfoVoList;
            const sourceIds = brandInfoVoList.map((item: any) => item.sourceId);
            const brandInfoBoList = data.brandInfoVoList || [];
            const arr: Record<string, any>[] = []; // 新增品牌
            brandInfoBoList.forEach((item: any) => {
              if (!sourceIds.includes(item.sourceId)) {
                item.customCategoryBo = item.customCategoryVo || {};
                item.channelsInfoBo = item.channelsInfoVo || {};
                arr.push(item);
              } else {
                const part = brandInfoVoList.find(
                  (sItem: any) => sItem.sourceId === item.sourceId
                );
                arr.push({
                  id: part.id,
                  brandDetails: item.brandDetails,
                  brandImage: item.brandImage,
                  brandLogo: item.brandLogo,
                  brandName: item.brandName,
                  customCategoryBo: {
                    ...item.customCategoryVo,
                    id: part.customCategoryVo.id
                  },
                  channelsInfoBo: {
                    ...item.channelsInfoVo,
                    id: part.channelsInfoVo.id
                  }
                });
              }
            });
            if (arr.length) {
              customerForm.value.brandInfoBoList = arr;
            } else {
              delete customerForm.value.brandInfoBoList;
            }

            const deleteSourceIds = brandInfoBoList.map(
              (item: any) => item.sourceId
            );
            const deleteArr: Record<string, any>[] = []; // 删除品牌
            brandInfoVoList.forEach((item: any) => {
              if (!deleteSourceIds.includes(item.sourceId)) {
                item.customCategoryBo = item.customCategoryVo || {};
                item.channelsInfoBo = item.channelsInfoVo || {};
                deleteArr.push(item);
              }
            });
            if (deleteArr.length) {
              customerForm.value.delBrandInfoBoList = deleteArr;
            } else {
              delete customerForm.value.delBrandInfoBoList;
            }
          }

          if (data.companyType === "3") {
            customerForm.value.externalTrade = data.externalTrade;
            customerForm.value.externalTradeRatio = data.externalTradeRatio;
            customerForm.value.customMade = data.customMade;
            customerForm.value.area = data.area;
            customerForm.value.serviceScope = data.serviceScope;
            customerForm.value.filings = data.filings;
            customerForm.value.annualOutput = data.annualOutput;
            customerForm.value.annualValue = data.annualValue;
            customerForm.value.researchStaffNum = data.researchStaffNum;
            customerForm.value.filingsNum = data.filingsNum;
            customerForm.value.engineer = data.engineer;
            customerForm.value.patent = data.patent;
            customerForm.value.minOrder = data.minOrder;
            customerForm.value.modelNum = data.modelNum;
            customerForm.value.packDesigners = data.packDesigners;
            customerForm.value.materialProductNum = data.materialProductNum;

            const partnerVoList = customerForm.value.partnerVoList;
            const partnerSourceIds = partnerVoList.map(
              (item: any) => item.sourceId
            );
            const partnerBoList = data.partnerVoList || [];
            const list: Record<string, any>[] = []; // 新增合作伙伴
            partnerBoList.forEach((item: any) => {
              if (!partnerSourceIds.includes(item.sourceId)) {
                list.push(item);
              } else {
                const part = partnerVoList.find(
                  (sItem: any) => sItem.sourceId === item.sourceId
                );
                list.push({
                  ...item,
                  id: part.id
                });
              }
            });
            if (list.length) {
              customerForm.value.partnerBoList = list;
            } else {
              delete customerForm.value.partnerBoList;
            }

            const deletePartnerIds = partnerBoList.map(
              (item: any) => item.sourceId
            );
            const deleteList: Record<string, any>[] = []; // 删除合作伙伴
            partnerVoList.forEach((item: any) => {
              if (!deletePartnerIds.includes(item.sourceId)) {
                deleteList.push(item);
              }
            });
            if (deleteList.length) {
              customerForm.value.delPartnerBoList = deleteList;
            } else {
              delete customerForm.value.delPartnerBoList;
            }
          }

          if (["3", "4", "5"].includes(data.companyType)) {
            if (!customerForm.value.customCategoryVo) {
              customerForm.value.customCategoryVo = {
                brandId: "",
                categoryOne: "",
                categoryTwo: "",
                mainPush: "",
                entityType: "",
                customId: "",
                id: ""
              };
            }
            if (!customerForm.value.id) {
              customerForm.value.customCategoryVo = data.customCategoryVo;
            } else {
              customerForm.value.customCategoryVo.brandId =
                data.customCategoryVo.brandId || "";
              customerForm.value.customCategoryVo.categoryOne =
                data.customCategoryVo.categoryOne || "";
              customerForm.value.customCategoryVo.categoryTwo =
                data.customCategoryVo.categoryTwo || "";
              customerForm.value.customCategoryVo.mainPush =
                data.customCategoryVo.mainPush || "";
              customerForm.value.customCategoryVo.entityType =
                data.customCategoryVo.entityType || "";
              customerForm.value.customCategoryVo.customId =
                data.customCategoryVo.customId || "";
            }
            customerForm.value.customCategoryBo =
              customerForm.value.customCategoryVo;
          }
        }
      }
    }
  );
}

function searchCustom() {
  if (!searchValue.value) return showToast("请输入企业名称");
  queryQccInfo(searchValue.value).then((res: any) => {
    console.log(res);
    if (+res.code === 200) {
      showToast("企查查同步成功");
      customerForm.value.qccSynDate = dayjs().format("YYYY-MM-DD HH:mm:ss");

      const data = res.data;
      if (!isCbe.value) {
        customerForm.value.customType = "2";
        customerForm.value.zhName = data.zhName;
        customerForm.value.zhShortName = data.zhShortName;
        customerForm.value.enName = data.enName;
        customerForm.value.briefIntro = data.briefIntro;
      }
      if (data.logo) customerForm.value.logo = data.logo;
      customerForm.value.no = data.no;
      customerForm.value.belongOrg = data.belongOrg;
      customerForm.value.operName = data.operName;
      customerForm.value.startDate = data.startDate;
      customerForm.value.endDate = data.endDate;
      customerForm.value.status = data.status;
      customerForm.value.province = data.province;
      customerForm.value.updatedDate = data.updatedDate;
      customerForm.value.updateTime = data.updateTime;
      customerForm.value.creditCode = data.creditCode;
      customerForm.value.registCapi = data.registCapi;
      customerForm.value.econKind = data.econKind;
      customerForm.value.address = data.address;
      customerForm.value.scope = data.scope;
      customerForm.value.termStart = data.termStart;
      customerForm.value.termEnd = data.termEnd;
      customerForm.value.checkDate = data.checkDate;
      customerForm.value.stockNumber = data.stockNumber;
      customerForm.value.recCap = data.recCap;
      customerForm.value.areaCode = data.areaCode;
      customerForm.value.isOnStock = data.isOnStock;
      customerForm.value.stockType = data.stockType;
      customerForm.value.entType = data.entType;

      if (!customerForm.value.customAreaVo) {
        customerForm.value.customAreaVo = {
          city: "",
          county: "",
          customId: "",
          province: "",
          id: ""
        };
      }
      if (!customerForm.value.revokeInfoVo) {
        customerForm.value.revokeInfoVo = {
          cancelDate: "",
          cancelReason: "",
          revokeDate: "",
          revokeReason: "",
          id: ""
        };
      }
      if (!customerForm.value.id) {
        customerForm.value.customAreaVo = data.customAreaVo;
        customerForm.value.revokeInfoVo = data.revokeInfoVo;
      } else {
        customerForm.value.customAreaVo.city = data.customAreaVo?.city;
        customerForm.value.customAreaVo.county = data.customAreaVo?.county;
        customerForm.value.customAreaVo.customId = data.customAreaVo?.customId;
        customerForm.value.customAreaVo.province = data.customAreaVo?.province;
        customerForm.value.customAreaBo = customerForm.value.customAreaVo;

        customerForm.value.revokeInfoVo.cancelDate =
          data.revokeInfoVo?.cancelDate;
        customerForm.value.revokeInfoVo.cancelReason =
          data.revokeInfoVo?.cancelReason;
        customerForm.value.revokeInfoVo.revokeDate =
          data.revokeInfoVo?.revokeDate;
        customerForm.value.revokeInfoVo.revokeReason =
          data.revokeInfoVo?.revokeReason;
        customerForm.value.revokeInfoBo = customerForm.value.revokeInfoVo;
      }

      const originalNameVoList = customerForm.value.originalNameVoList;
      const names = originalNameVoList.map((item: any) => item.name);
      const originalNameBoList = data.originalNameVoList || [];
      const arr: Record<string, any>[] = [];
      originalNameBoList.forEach((item: any) => {
        if (!names.includes(item.name)) {
          arr.push(item);
        } else {
          const part = originalNameVoList.find(
            (sItem: any) => sItem.name === item.name
          );
          arr.push({
            ...item,
            id: part.id
          });
        }
      });
      if (arr.length) {
        customerForm.value.originalNameBoList = arr;
      } else {
        delete customerForm.value.originalNameBoList;
      }

      const deleteNames = originalNameBoList.map((item: any) => item.name);
      const deleteList: Record<string, any>[] = [];
      originalNameVoList.forEach((item: any) => {
        if (!deleteNames.includes(item.name)) {
          deleteList.push(item);
        }
      });
      if (deleteList.length) {
        customerForm.value.delOriginalNameBoList = deleteList;
      } else {
        delete customerForm.value.delOriginalNameBoList;
      }
    }
  });
}

function onSubmit() {
  // 词条新增
  customerForm.value.contentBoList = [];
  entryList.value.forEach((item: any) => {
    const content =
      item.entryType === "3" ? item.content.join(",") : item.content;
    if (content) {
      const part = customerForm.value.contentVoList.find(
        (sItem: any) => sItem?.entryId === item.id
      );
      customerForm.value.contentBoList.push({
        id: part?.id,
        entryId: item.id,
        content
      });
    }
  });
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    overlay: true,
    message: "提交中..."
  });
  if (customerForm.value.id) {
    updateCustom(customerForm.value)
      .then((res: any) => {
        console.log(res);
        if (+res.code === 200) {
          showSuccessToast("修改成功");
          setTimeout(() => {
            userStore.customInfo = {};
            router.back();
          }, 1000);
        }
      })
      .finally(() => {
        closeToast();
      });
  } else {
    saveCustom(customerForm.value)
      .then((res: any) => {
        console.log(res);
        if (+res.code === 200) {
          showSuccessToast("新增成功");
          if (customId.value) {
            setTimeout(() => {
              userStore.customInfo = {};
              router.back();
            }, 1000);
          } else {
            setTimeout(() => {
              router.push("home");
            }, 1000);
          }
        }
      })
      .finally(() => {
        closeToast();
      });
  }
}

loading.value = true;
entryGetList()
  .then(res => {
    entryList.value = res.data || [];
    entryList.value.forEach(item => {
      item.content = "";
      if (item.entryType === "3") item.content = [];
    });
  })
  .finally(() => (loading.value = false));

dictListAll("custom_type").then(res => {
  custom_type.value = res.data || [];
});

dictListAll("company_type").then(res => {
  company_type.value = res.data || [];
});

// 词条信息回显
watch([() => entryList.value, () => customerForm.value.contentVoList], () => {
  entryList.value.forEach((item: any) => {
    if (Array.isArray(customerForm.value.contentVoList)) {
      if (customerForm.value.contentVoList.length) {
        customerForm.value.contentVoList.forEach((sItem: any) => {
          if (sItem && sItem.entryId === item.id) {
            item.content = sItem.content;
            if (item.entryType === "3")
              item.content = sItem && sItem.content.split(",");
          }
        });
      } else {
        entryList.value.forEach(item => {
          item.content = "";
          if (item.entryType === "3") item.content = [];
        });
      }
    }
  });
});

watch(
  () => route.query,
  () => {
    if (JSON.stringify(userStore.customInfo) === "{}" && customId.value) {
      customDetail(customId.value).then(res => {
        userStore.customInfo = res.data;
      });
    }
  },
  { immediate: true }
);

watch(
  () => userStore.customInfo,
  (val: any) => {
    if (JSON.stringify(val) === "{}") {
      searchValue.value = "";
      customerForm.value = initForm();
      return;
    }
    customerForm.value = val;
    customerForm.value = val?.id ? val : initForm();
    customerForm.value.customType = val.id ? val.customType || "2" : "";
    isCbe.value = customerForm.value.customType === "1";
    customerForm.value.contentVoList = val.contentVoList || [];
    customerForm.value.brandInfoVoList = val.brandInfoVoList || [];
    customerForm.value.partnerVoList = val.partnerVoList || [];
    customerForm.value.originalNameVoList = val.originalNameVoList || [];
    searchValue.value = customerForm.value.zhName;
  },
  { immediate: true }
);
</script>

<style scoped lang="less">
.custom-detail {
  position: relative;
  width: 100%;
  background-color: #f3f4fa;

  .custom-detail-main {
    position: absolute;
    top: 4rem;
    left: 0;
    width: 100%;
    height: calc(100% - 4rem);
    display: flex;
    flex-direction: column;
    padding: 1rem;
    background-color: #fff;
    overflow: auto;

    :deep(.search-input.van-cell) {
      padding-right: 0;
    }

    .radio-box :deep(.van-radio) {
      margin-bottom: 0.5rem;
    }
  }
}
</style>
